/**
 * 
 */
package validators;

import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import utils.TechresourceDAORemote;

/**
 * Validator that validates if an ip address is not empty, correctly formated, and not yet in use.
 * 
 * @author Szekely Krisztian-Vilmos
 *
 */
@FacesValidator("validators.IpValidator")
public class IpValidator implements Validator {
	@EJB
	TechresourceDAORemote tr;
	
	private Pattern pattern;
	private Matcher matcher;
	
	private final static String IP_PATTERN = "(\\d{1,3}\\.){3}\\d{1,3}";

	ResourceBundle bundle = ResourceBundle.getBundle(
			"languageSettings.language", FacesContext.getCurrentInstance()
					.getViewRoot().getLocale());
	
	public IpValidator() {
		pattern = Pattern.compile(IP_PATTERN);
	}
	
	/**
	 * @see javax.faces.validator.Validator#validate(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
	 **/
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		
		String val = value.toString();
		
		if (val.length() == 0) {
			FacesMessage message = new FacesMessage(bundle.getString("Validators_IpValidator_Error1"));
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		} else {
			matcher = pattern.matcher(val);
			
			if (!matcher.matches()) {
				FacesMessage message = new FacesMessage(bundle.getString("Validators_IpValidator_Error2"));
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
				throw new ValidatorException(message);
			} else {
				if (tr.getTechResourcesDTOByIp(val).size() > 0) {
					FacesMessage message = new FacesMessage(bundle.getString("Validators_IpValidator_Error3"));
					message.setSeverity(FacesMessage.SEVERITY_ERROR);
					throw new ValidatorException(message);
				}
			} 
		}
	}
	
}
